package com.wframe.project.jnd.services.impl;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.frame.database.JdataBean;
import com.frame.database.PageResult;
import com.wframe.project.jnd.dao.IntegralDao;
import com.wframe.project.jnd.entity.Integral;
import com.wframe.project.jnd.services.CouponService;
import com.wframe.project.jnd.services.IntegralService;
import com.wframe.project.jnd.vo.IntegralRulesVo;
import com.wframe.project.jnd.wx.constant.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Administrator on 2017/7/31.
 */
@Service
public class IntegralServiceImpl implements IntegralService {
    @Autowired
    IntegralDao integralDao;
    @Autowired
    CouponService couponService;
    @Override
    public PageResult queryIntegralList(JdataBean parms, int pagesize, int pageno) throws Exception {
        return integralDao.queryIntegralList(parms, pagesize, pageno);
    }

    @Override
    public List<JdataBean> queryWXIntegralList(String userid) {
        return integralDao.queryWXIntegralList(userid);
    }

    /**
     * 查看用户的积分
     * @param userid
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public JdataBean queryUserIntegrals(String userid) throws Exception{
        if(StringUtils.isBlank(userid)) {
            return null;
        }
        JdataBean userIntegral = integralDao.queryUserIntegrals(userid);
        int year = userIntegral.getInt("now_year");
        if(StringUtils.isNotBlank(userIntegral.getString("this_year"))) {
            int this_year = userIntegral.getInt("this_year");
            if (year == this_year) {
                return userIntegral;
            }else {
                //更新用户的积分
                Map<String, String> key = new HashMap<>();
                key.put("id", userid);
                JdataBean parms = new JdataBean();
                parms.put("this_year", year);
                parms.put("integral", 0.00);
                parms.put("ly_integral",userIntegral.get("integral"));
                integralDao.update("wbuser", parms.getDataMap(), key);
                return integralDao.queryUserIntegrals(userid);
            }
        }else {
            Map<String, String> key = new HashMap<>();
            key.put("id", userid);
            JdataBean parms = new JdataBean();
            parms.put("this_year", year);
            integralDao.update("wbuser", parms.getDataMap(), key);
            return userIntegral;
        }
    }

    @Override
    public List<JdataBean> queryExchangeCoupon() {
        return integralDao.queryExchangeCoupon();
    }

    /**
     * 积分兑换优惠卷
     * @param userid
     * @param couponid
     * @param platform
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public String exchangeCoupon(String userid, String couponid, Integer platform) throws Exception{
        if(StringUtils.isBlank(userid) || StringUtils.isBlank(couponid)) {
            return "用户或优惠卷不存在";
        }
        JdataBean coupon = integralDao.queryExchangeCoupon(couponid);
        if(coupon != null) {
            BigDecimal offer_money = coupon.getBigDecimal("offer_money").multiply(new BigDecimal(100));

           String update_integral = "-" + offer_money;
           JdataBean parms = new JdataBean();
           parms.put("type", Integral.Type.EXCHANGE.ordinal());
           parms.put("content","兑换优惠卷");
           parms.put("platform",platform);
           if(updateUserIntegral(userid, update_integral,parms)) {
               couponService.receiveCoupon(coupon, userid, Constant.COUPON_SOURCE_EXCHANGE);
               return "优惠券兑换成功";
           }else {
               return "您当前积分不足以兑换该优惠券";
           }
        }

        return "该优惠卷已兑完";
    }

    /**
     * 更改用户的积分
     * @param userid 用户id
     * @param integral 修改的积分数,当减少积分时,积分数应为负数的字符串
     * @param parms 积分的其他信息,例如:积分的新增方式type
     * @return Boolean 操作成功返回true,失败返回false
     * @throws Exception
     */
    @Override
    @Transactional
    public Boolean updateUserIntegral(String userid, String integral, JdataBean parms) throws Exception {
        if(StringUtils.isNotBlank(userid) && StringUtils.isNotBlank(integral)) {
            BigDecimal update_integral = new BigDecimal(integral);
            JdataBean userIntegral = queryUserIntegrals(userid);
            BigDecimal ty_integral = userIntegral.getBigDecimal("integral");
            BigDecimal ly_integral = userIntegral.getBigDecimal("ly_integral");
            BigDecimal integralSum = ty_integral.add(ly_integral);
            Map<String, String> key = new HashMap<>();
            key.put("id", userid);
            Map<String, Object> userData = new HashMap<>();

            if(update_integral.compareTo(new BigDecimal(0)) >= 0) {
                userData.put("integral",ty_integral.add(update_integral));
            }else {
                if(integralSum.compareTo(update_integral.abs()) < 0) {
                    return false;
                }
                if(ly_integral.compareTo(update_integral.abs()) < 0){
                    userData.put("integral", ty_integral.add(ly_integral).add(update_integral));
                    userData.put("ly_integral", 0);
                }else {
                    userData.put("ly_integral", ly_integral.add(update_integral));
                }
            }

            integralDao.update("wbuser", userData, key);

            if(StringUtils.isBlank(parms.getString("create_time"))) {
                parms.put("create_time", new Date());
            }
            parms.put("userid", userid);
            parms.put("integral", update_integral);
            integralDao.saveReturnKey("wb_integral", parms.getDataMap());
            return true;
        }
        return false;
    }

    /**
     * 获取积分规则的数据
     * @return
     */
    @Override
    public JdataBean getIntegralRules() {
        List<JdataBean> rulesData = integralDao.getIntegralRules();
        JdataBean rules = new JdataBean();
        for(JdataBean data : rulesData) {
            if("integral_today".equals(data.getString("code"))) {
                rules.put("integral_today",data.getString("val"));
            }
            if("integral_register".equals(data.getString("code"))) {
                rules.put("integral_register",data.getString("val"));
            }
            if("integral_scale".equals(data.getString("code"))) {
                rules.put("integral_scale",data.getString("val"));
            }
            if("integral_rule".equals(data.getString("code"))) {
               String val = data.getString("val");
               List<IntegralRulesVo> list = JSON.parseArray(val, IntegralRulesVo.class);
               Map<Integer, Integer> day_integral = new HashMap<>();
               for(int i = 0 ; i < list.size() ; i++) {
                   day_integral.put(list.get(i).getDay(), list.get(i).getIntegral());
               }
               Set set = day_integral.keySet();
               List<Integer> days = new ArrayList<>();
               days.addAll(set);
               Collections.sort(days);
               rules.put("days", days);
               rules.put("days_integrals",day_integral);
               rules.put("list",list);
            }
        }
        return rules;
    }


}
